package com.qianya.system.manage.util;

import ch.qos.logback.core.util.CloseUtil;
import cn.hutool.core.date.DateUtil;
import com.qianya.util.SystemConfig;
import io.micrometer.core.instrument.util.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MysqlBackUpUtils {
//    private String URL="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&&serverTimezone=UTC";
//    private String USERNAME="root";
//    private String PASSWORD="123456";
    @Value("${spring.datasource.url}")
    private String URL;
    @Value("${spring.datasource.username}")
    private String USERNAME;
    @Value("${spring.datasource.password}")
    private String PASSWORD;
    @Value("${spring.datasource.driver-class-name}")
    private String DRIVERNAME;

    private static Log log = LogFactory.getLog(MysqlBackUpUtils.class);

    /**
     * description  获取mysql服务器信息
     * date         202011/08 下午 3:35
     * @author      lhl
     */
    private String[] getHostInfo(){
        String hostName="localhost";
        String port="3306";
        String database="medic_smart_spills";
        return new String[]{hostName, port, database};
    }

    /**
     * description  获取mysql安装路径
     * date         202011/08 下午 3:36
     * @author      lhl
     */
    private String getMysqlDir() throws SQLException {
        String dir = null;
        Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
        Statement stmt = connection.createStatement();
        ResultSet rs = stmt.executeQuery("select @@basedir as basePath from dual");
        while (rs.next()){
            dir = rs.getString("basePath");
        }
        rs.close();
        stmt.close();
        connection.close();
        StringBuilder sb = new StringBuilder(dir);
        if(!dir.substring(dir.length() - 1).equals(File.separator)){
            sb.append(File.separator); //如果最后没有/的话补齐
        }
        sb.append("bin");
        return sb.toString();
    }

    public boolean backup() throws SQLException {
        return run(true,null);
    }

    public boolean recover(String path) throws SQLException {
        return run(false,path);
    }

    private boolean run(boolean backup,String path) throws SQLException {
        boolean res = false;
        File runPath = new File(getMysqlDir());
        if(!runPath.exists()){
        	return false;
        }
        Runtime runtime = Runtime.getRuntime();
        InputStream input = null;
        InputStream errorStream = null;
        try {
            String[] cmd;
            if(backup){
                cmd = getBackupCmd();
            }else{
                File file = new File(path);
                if(!file.exists()) return false;
                cmd = getRecoverCmd(path);
            }
            Process process = runtime.exec(cmd,null, runPath);
            //若有错误信息则输出
            errorStream = process.getErrorStream();
            log.error(IOUtils.toString(errorStream, Charset.forName("GBK")));
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CloseUtil.closeQuietly(errorStream);
            CloseUtil.closeQuietly(input);
        }
        return res;

    }

    /**
     * description  获取备份指令
     * date         202011/08 下午 3:36
     * @author      lhl
     */
    private String[] getBackupCmd(){
        String[] hostInfo = getHostInfo();
        String path = SystemConfig.filePath() + "database" + File.separator + getDateStrToday();
        File saveDir = new File(path);
        if(!saveDir.exists()) saveDir.mkdirs();
        //StringBuilder cmd = new StringBuilder("cmd /c ");
        StringBuilder cmd = new StringBuilder("");
        cmd.append("mysqldump --add-drop-table -h ")
                .append(hostInfo[0]) //服务器
                .append(" -u").append(USERNAME) //用户名
                .append(" -p").append(PASSWORD) //密码
                .append(" ").append(hostInfo[2]) //数据库表
                .append(" -r").append(path.replace(" ","")).append(File.separator).append(getDateStr()).append(".sql"); //输出文件
        return new String[]{"sh", "-c", cmd.toString()};
    }

    /**
     * description  获取恢复指令
     * date         202011/08 下午 3:36
     * @author      lhl
     */
    private String[] getRecoverCmd(String path){
        String[] hostInfo = getHostInfo();
        //StringBuilder cmd = new StringBuilder("cmd /c ");
        StringBuilder cmd = new StringBuilder("");
        cmd.append("mysql -h ")
                .append(hostInfo[0]) //服务器
                .append(" -u").append(USERNAME) //用户名
                .append(" -p").append(PASSWORD) //密码
                .append(" --default-character-set=utf8 ").append(hostInfo[2]); //数据库表
        cmd.append(" <").append(path); //导入文件
        return new String[]{"sh", "-c", cmd.toString()};
    }

    /*当前时间字符串*/
    private String getDateStr(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }
    /*当前时间字符串*/
    private String getDateStrToday(){
        Date date=new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

}
